package com.kdgc.energy.dmm.query;

import com.kdgc.energy.dmm.Environment;
import com.kdgc.energy.dmm.result.QueryResult;
import com.kdgc.energy.dmm.time.TimeStatistical;
import org.apache.metamodel.data.DataSet;
import org.apache.metamodel.jdbc.JdbcDataContext;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 原生sql语句查询
 *
 * @author xu.wenchang
 * @version 1.0 2022/04/22
 */
public class SQLQuery {
    private String sql;
    
    private List<Class<?>> classes;
    
    private TimeStatistical timeStatistical;
    
    private SQLQuery() {
        this.timeStatistical = new TimeStatistical();
    }
    
    public SQLQuery(Class<?> entityClass) {
        this.classes = Collections.singletonList(entityClass);
        Environment.get(entityClass);
    }
    
    public SQLQuery(Class<?> entityClass, Class<?>... entityClasses) {
        this.classes = new ArrayList<>();
        this.classes.add(entityClass);
        Environment.get(entityClass);
        
        for (Class<?> clazz : entityClasses) {
            this.classes.add(clazz);
            Environment.get(clazz);
        }
    }
    
    public SQLQuery sql(String sql) {
        this.sql = sql;
        return this;
    }
    
    public QueryResult execute() {
        JdbcDataContext ctx = new JdbcDataContext(Environment.getDataSource());
        this.timeStatistical.phaseStart("execute");
        DataSet dataSet = ctx.executeQuery(this.sql);
        this.timeStatistical.phaseEnd("execute");
        return new QueryResult(this.timeStatistical, this.sql, dataSet);
    }
}
